package org.aurora.eleven;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author : Aurora
 * @date : 2024/3/27 14:36
 * @description
 */
public class ConcurrentHashMapPractice {
    static ConcurrentHashMap<String, List<String>> map = new ConcurrentHashMap<>();

    public static void main(String[] args) {
//        version1();
        version2();
    }
    public static void version1(){
        //进入直播间topic1，线程one
        Thread threadOne = new Thread(() -> {
            List<String> list1 = new ArrayList<>();
            list1.add("device1");
            list1.add("device2");
            map.put("topic1", list1);
            System.out.println(JSON.toJSONString(map));
        });
        //进入直播间topic1，线程two
        Thread threadTwo = new Thread(() -> {
            List<String> list1 = new ArrayList<>();
            list1.add("device11");
            list1.add("device22");
            map.put("topic1", list1);
            System.out.println(JSON.toJSONString(map));
        });
        //进入直播间topic2，线程three
        Thread threadThree = new Thread(() -> {
            List<String> list1 = new ArrayList<>();
            list1.add("device111");
            list1.add("device222");
            map.put("topic2", list1);
            System.out.println(JSON.toJSONString(map));
        });
        threadOne.start();
        threadTwo.start();
        threadThree.start();
    }

    public static void version2(){
        //进入直播间topic1，线程one
        Thread threadOne = new Thread(() -> {
            List<String> list1 = new ArrayList<>();
            list1.add("device1");
            list1.add("device2");
            List<String> oldList = map.putIfAbsent("topic1", list1);
            if(null != oldList){
                oldList.addAll(list1);
            }
            System.out.println(JSON.toJSONString(map));
        });
        //进入直播间topic1，线程two
        Thread threadTwo = new Thread(() -> {
            List<String> list1 = new ArrayList<>();
            list1.add("device11");
            list1.add("device22");
            List<String> oldList = map.putIfAbsent("topic1", list1);
            if(null != oldList){
                oldList.addAll(list1);
            }
            System.out.println(JSON.toJSONString(map));
        });
        //进入直播间topic2，线程three
        Thread threadThree = new Thread(() -> {
            List<String> list1 = new ArrayList<>();
            list1.add("device111");
            list1.add("device222");
            List<String> oldList = map.putIfAbsent("topic2", list1);
            if(null != oldList){
                oldList.addAll(list1);
            }
            System.out.println(JSON.toJSONString(map));
        });
        threadOne.start();
        threadTwo.start();
        threadThree.start();
    }

}
